package main;

import java.util.StringTokenizer;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Represents a node in the task graph 
 *
 */
public class Task implements Runnable {
	private String id;
	private Command command;

	private LinkedBlockingQueue<Task> predecessors;
	public boolean executing = true;
	
	public Task(String id, String command) {
		StringTokenizer tokens = new StringTokenizer(command);
		if (tokens.countTokens() > 2) throw new IllegalArgumentException();
		
		this.id = id;
		this.command = new Command(tokens.nextToken(), tokens.nextToken());
		this.predecessors = new LinkedBlockingQueue<Task>();
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public void setCommand(Command command) {
		this.command = command;
	}
	public Command getCommand() {
		return command;
	}

	public void addPredecessor(Task task) {
		predecessors.add(task);
	}
	public LinkedBlockingQueue<Task> getPredecessors() {
		return predecessors;
	}
	
	@Override
	public void run() {
		long startTime = System.currentTimeMillis();
		System.err.print("LOCAL>>> ");
		System.err.println("Executing " + this + "...");
		executing = true;
		command.execute();
		executing = false;
		synchronized(this) {
			notify();
		}
		long finishTime = System.currentTimeMillis();
		Main.totalTime += finishTime - startTime;
	}

	@Override
	public String toString() {
		return "<" + 
				((id.length() > 0) ? id + ": " : "") +
				command.toString() + ">";
	}

}
